from tortoise import models, fields


class UserModel(models.Model):
    id = fields.IntField(pk=True)
    username = fields.CharField(max_length=50, unique=True, description="用户名")
    password = fields.CharField(max_length=100, description="密码")
    nickname = fields.CharField(max_length=50, null=True, description="昵称")
    email = fields.CharField(max_length=100, null=True, description="邮箱")
    posts = fields.ReverseRelation["PostModel"]  # 明示 1vs多 反向关联关系 可选

    def __str__(self):
        return self.nickname or self.username

    class Meta:
        table = "users"
        table_description = "用户表"


# 1vs many关系 关联关系在多方定义
class PostModel(models.Model):
    id = fields.IntField(pk=True)
    title = fields.CharField(max_length=100, description="标题")
    content = fields.TextField(description="内容")
    user = fields.ForeignKeyField("models.UserModel", related_name="posts", description="作者")  # 关联关系

    def __str__(self):
        return self.title

    class Meta:
        table = "posts"
        table_description = "文章表"


# 1vs1关系
class UserInfoModel(models.Model):
    id = fields.IntField(pk=True)
    sex = fields.CharField(max_length=10, description="性别")
    birth_date = fields.DateField(description="出生日期")
    phone = fields.CharField(max_length=20, description="手机号")
    age = fields.IntField(description="年龄")
    address = fields.CharField(max_length=100, description="地址")
    user = fields.OneToOneField("models.UserModel", related_name="info", description="用户信息")  # 关联关系

    def __str__(self):
        return self.user.username + "的个人信息"

    class Meta:
        table = "user_info"
        table_description = "用户信息表"


# 多vs多关系 微信群聊关系
class CommunityModel(models.Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=50, description="群名称")
    # 多vs多关系
    members = fields.ManyToManyField("models.UserModel", related_name="communities", description="群成员")

    def __str__(self):
        return self.name

    class Meta:
        table = "communities"
        table_description = "社群表"
